<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2019-04-10
 * Time: 17:55
 */

namespace app\api\controller;

use app\common\model\Loginstatus;
use app\service\LogService;
use app\service\MoneylogService;
use app\service\OrderService;
use app\service\UserService;
use app\service\WechatService;
use app\service\PayService;
use app\common\model\Order as OrderModel;
use app\common\model\User as UserModel;
use app\common\model\Daily;
use app\common\model\WechatTmplLog as WechatTmplLogModel;
use app\service\MsgService;
use app\common\model\UnionOrder;
use think\Db;
use app\common\model\Alipay;


use EasyWeChat\Kernel\Messages\NewsItem;

use EasyWeChat\Factory;

class Notify extends AllBase
{

    public $payment;

    public function __construct()
    {
        parent::__construct();
    }

    /* 接收微信支付成功事件 */
    public function wechat()
    {
        $input = file_get_contents('php://input');
        //file_put_contents(ROOT_PATH.'log.txt',$input.PHP_EOL,FILE_APPEND);
        return PayService::S(['mall_id' => 1])->wechatPaySuccess($input);
    }

    /* 接收微信支付成功事件 */
    public function money()
    {
        $input = file_get_contents('php://input');

        //file_put_contents(ROOT_PATH.'log.txt',$input.PHP_EOL,FILE_APPEND);
        return PayService::S(['mall_id' => 1])->wechatMoneySuccess($input);
    }

    /* 接收微信支付成功事件 */
    public function video()
    {
        $input = file_get_contents('php://input');

        //file_put_contents(ROOT_PATH.'log.txt',$input.PHP_EOL,FILE_APPEND);
        return PayService::S(['mall_id' => 1])->wechatVideoSuccess($input);
    }

    /* 转码完成 */
    public function amr()
    {
        model('qiniu')->remove(input('inputKey'));
        LogService::S()->writeLog('amr', '', json_encode(input()));
    }

    /* 定时发送模板消息 */
    public function send()
    {
        $list = WechatTmplLogModel::getAll(['status' => 0]);
        foreach ($list as $v) {
            MsgService::S(['mall_id' => $v['mall_id']])->send($v);
        }
    }


    /* 联盟订单 */
    public function unionOrder()
    {
        $input = file_get_contents('php://input');
        if (!$input) {
            exit;
        }
        $key = config('union_key');
        $input = json_decode($input, true);
        $params = $input;
        unset($params['sign']);
        unset($params['content']);
        $sign = UnionOrder::_getSign($params, $key);
        if ($sign != $input['sign']) {
            exit('sign is error');
        }
        $order = $input;
        unset($order['sign']);
        $oldOrder = UnionOrder::getOne([
            'order_id' => $order['order_id']
        ]);
        $order['self_money'] = round($order['money'] * config('union_jd_bili'), 2);//本人返利
        $mallMoney = round($order['money'] * config('union_jd_mall_bili'), 2);//分公司返利
        $referMoney = round($order['money'] * config('union_jd_refer_bili'), 2);//代理商返利
        if ($oldOrder) {
            UnionOrder::where([
                'order_id' => $order['order_id']
            ])->update($order);
            if ($oldOrder['status'] != 18 && $order['status'] == 18 && $order['type'] == 'jd') {
                //第一次状态变为已结算
                $content = "生态商城订单返利(订单号:{$order['order_id']})";
                UserModel::changeMoney($order['union_uid'], 3, $order['self_money'], $content);

                //代理商奖励
                $content = "生态商城订单代理商奖励(订单号:{$order['order_id']})";
                $referInfo = UserModel::getFirstRefer($order['union_uid'], 2);
                if ($referInfo) {
                    UserModel::changeMoney($referInfo['id'], 1, $referMoney, $content);
                }
                /*
                        //分公司奖励
                        $mall = UserModel::getFirstRefer($order['union_mall_id'],3,true);
                        if(!$mall) {
                          $mall = Mall::getOneById($order['union_mall_id']-100);
                        }
                        if($mall) {
                          $content = "京东订单分公司奖励(订单号:{$order['order_id']})";
                          if($mall['uid']) {
                            UserModel::changeMoney($mall['uid'],1,$mallMoney,$content);
                          }
                        } */
            } else if ($oldOrder['status'] != 5 && $order['status'] == 5 && $order['type'] == 'pdd') {
                $content = "生态商城订单返利(订单号:{$order['order_id']})";
                UserModel::changeMoney($order['union_uid'], 3, $order['self_money'], $content);

                //代理商奖励
                $content = "生态商城订单代理商奖励(订单号:{$order['order_id']})";
                $referInfo = UserModel::getFirstRefer($order['union_uid'], 2);
                if ($referInfo) {
                    UserModel::changeMoney($referInfo['id'], 1, $referMoney, $content);
                }
            }
        } else {
            UnionOrder::create($order);
        }
        return $order['order_id'];
    }


    /* 常用定时任务一起执行 */
    public function cronAll()
    {
        OrderModel::cancelOrder();//取消超时订单
        OrderModel::shouhuoOrder();//确认收货
        Daily::tongji();//每日统计
    }

    public function kefu_msg()
    {
        $id = input("id");

        $moneyLog = MoneylogService::S()->find_log($id);
        //dump($moneyLog);die;
        $userInfo = UserService::S()->findUser(array('id' => $moneyLog['uid']));


        $obj = WechatService::S([
            'mall_id' => $userInfo['mall_id']
        ]);

        $recentList = Loginstatus::getAll([
            'update_time' => [
                'egt', time() - 3600 * 24
            ],
            'mall_id' => $userInfo['mall_id']
        ], "", "uid");
        // dump($recentList);die;
        //$recentList = UserModel::getRencentList($moneyLog['uid']);
        //LogService::S()->writeLog("st",'ts',$recentList);
        if ($recentList) {
            foreach ($recentList as $v) {
                $re = $obj->send(
                    2,
                    UserModel::uid2openid($v['uid']),
                    [new NewsItem([
                        'title' => $userInfo['nickname'] . "在群内发了一个红包,快来抢红包吧",
                        'description' => '',
                        'url' => request()->domain() . "/m/chat/pages/index/index?rid=" . $moneyLog['id'] . "&mall_id={$userInfo['mall_id']}",
                        'image' => "http://cdn.1s1s.club/shopcom/20190510/1725488242.png",
                    ])]
                );
                LogService::S()->writeLog('result', 'code1', $re);
            }
        }

    }


    /* 分公司充值回调 */
    public function alipaycallback()
    {
        LogService::S()->writeLog('alipaycallback', 'alipayrecharge', $_POST);
        //echo "fail";exit;
        //$json = '{"gmt_create":"2019-09-05 18:15:59","charset":"utf-8","gmt_payment":"2019-09-05 18:16:03","notify_time":"2019-09-05 18:16:03","subject":"\u5546\u54c1\u79ef\u5206\u5145\u503c","sign":"m7uqqBTp0phI82HloNoYB4LCIIGmSLHqbNP8mbUts\/SZmB+u+KLrftYlpkplZEmfvKbt1rYRN8avTshATWnQTe4YS9QBEDepKcD0BZBLpD5kqXODSJGFGsNPT77MHACWQbJj5NpbSOpIHODCk9jM3U2vmvjJR1pJ1z8BRGJCbtHAfwjFB4PEQZ1US9JS4n0Ph5JyHFcjPZRvk500ufp1TqS66iu4xyN+iNdrmV8zvwdaC3lqxtscoL9Qb1qHMIZGKV7kymm3wW3GpEqE5ztQEHY0vjTjdiIz8xSl7lNloYnbSD2TPIxHo+fnSnxseRrMzEeaB+nVQGV3g1Ou3HiAyA==","buyer_id":"2088432457562952","invoice_amount":"0.10","version":"1.0","notify_id":"2019090500222181603062950555712542","fund_bill_list":"[{\"amount\":\"0.10\",\"fundChannel\":\"ALIPAYACCOUNT\"}]","notify_type":"trade_status_sync","out_trade_no":"201909051815411683","total_amount":"0.10","trade_status":"TRADE_SUCCESS","trade_no":"2019090522001462950572723623","auth_app_id":"2018032702456663","receipt_amount":"0.10","point_amount":"0.00","buyer_pay_amount":"0.10","app_id":"2018032702456663","sign_type":"RSA2","seller_id":"2088031710847205"}';
        //$data = json_decode($json,true);
        $data = $_POST;

        if (!is_array($data)) {
            $data = json_decode($data, true);
        }
        $where = array(
            "order_sn" => $data['out_trade_no']
        );
        //查找订单
        $order = Db::name('order_recharge')->where($where)->find();
        if (empty($order)) {
            echo "fail";
            exit;
        }
        //LogService::S()->writeLog('alipaycallback','alipayrecharge',$_POST);
        $alipay = new Alipay();
        $res = $alipay->checkSignNew($data);
        if (!$res) {
            echo "fail";
            exit;
        } else {
            if ($order['checked'] == 0) {
                //修改状态
                $save['checked'] = 1;
                $save['pay_time'] = date('Y-m-d H:i:s');
                $save['charge_data'] = json_encode($_POST);
                Db::name('order_recharge')->where($where)->update($save);
                //写入充值日志
                Db::name('mall')->where(array('id' => $order['mall_id']))->setInc('money', $order['money']);
            }
            echo "success";
        }
    }

}